<template>
  <view>
    <view class="problem-title">{{ problem }}</view>
    <view class="wrap">
      <view>
        {{ answer }}
      </view>
      <view class="bottom-bar">
        <view class="left" @tap.stop="jumpEnAnswerPage">
          <image
            src="@/static/imgs/icons/translate_icon.png"
            mode="widthFix"
          ></image>
          <text>英语回答</text>
        </view>
        <view class="right">
          <image
            src="@/static/imgs/icons/play_icon.png"
            mode="widthFix"
            @tap.stop="onPlayIconClick"
          ></image>
          <button open-type="share">
            <image
              src="@/static/imgs/icons/share_icon.png"
              mode="widthFix"
            ></image>
          </button>
          <image
            src="@/static/imgs/icons/copy_icon.png"
            mode="widthFix"
            @tap.stop="onCopyIconClick"
          ></image>
          <image
            :src="zanIconUrl"
            mode="widthFix"
            @tap.stop="onZanIconClick"
          ></image>
          <image
            :src="caiIconUrl"
            mode="widthFix"
            @tap.stop="onCaiIconClick"
          ></image>
        </view>
      </view>
    </view>
  </view>

  <bottomEnter />
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { tnNavPage } from '@tuniao/tnui-vue3-uniapp/utils'
import { bottomEnter } from '@/components/bottom-enter'
import { onLoad, onHide, onUnload, onPageHide } from '@dcloudio/uni-app'
import storageApi from '@/utils/storage'
import { voteDown, voteUp, selectIsVote } from '@/services/api'
import { useWebsocket } from '@/hooks'
import { BASE_URL } from '@/config'
var plugin = requirePlugin('WechatSI')
let manager = plugin.getRecordRecognitionManager()

const innerAudioContext = uni.createInnerAudioContext()
const { handleClickVideo, webSocketSendMp3, handleCloseVideo } = useWebsocket()

const problem = ref('')
const answer = ref('')
const audioSrc = ref('')
const pageId = ref('')
//voteStatus，0,没操作 1点赞  2点踩
const voteStatus = ref('')
const zanIconUrl = ref('../../static/imgs/icons/zan_icon.png')
const caiIconUrl = ref('../../static/imgs/icons/cai_icon.png')
const messages = ref([
  { content: '请输入您的问题或需求，我随时帮你解答', type: 'system' },
])
const messagesBack = ref([
  { content: '请输入您的问题或需求，我随时帮你解答', role: 'system' },
])
//此数组用于推荐问题
const chatArr = reactive({
  messages: [
    {
      role: 'assistant',
      content: '请输入您的问题或需求，我随时帮你解答',
    },
  ],
})

onLoad((option) => {
  problem.value = option.problem
  pageId.value = option.pageId
  sendMessage(`${problem.value}，请用200字以内简短回答`)
  getIsVote()
})

onHide(() => {
  handleCloseVideo()
})

onUnload(() => {
  handleCloseVideo()
})

const getIsVote = () => {
  selectIsVote(pageId.value).then((res) => {
    const { code, status } = res
    if (code === 0) {
      voteStatus.value = status
      if (voteStatus.value === 1) {
        zanIconUrl.value = '../../static/imgs/icons/zan_icon_checked.png'
      }
      if (voteStatus.value === 2) {
        caiIconUrl.value = '../../static/imgs/icons/cai_icon_checked.png'
      }
    }
  })
}

// 发送输入的问题
const sendMessage = (context) => {
  if (messages.value.length == 1) {
    messages.value = []
  }
  if (context.trim() !== '') {
    messages.value.push({ content: context, role: 'user' })
    messagesBack.value.push({ content: context, role: 'user' })
    chatArr.messages.push({ content: context, role: 'user' })
    let data = {
      messages: messagesBack.value,
    }
    // uni.showLoading({
    //   title: '分析问题中...',
    // })
    const requestTask = uni.request({
      url: `${BASE_URL}/enteacher/aichat`,
      timeout: 15000,
      responseType: 'text',
      method: 'POST',
      enableChunked: true,
      data: data,
      success: (response) => {
        console.log(response)
      },
      fail: (error) => {},
    })
    requestTask.onHeadersReceived(function (res) {
      console.log(456)
      console.log(res.header)
    })

    // 这里监听消息
    requestTask.onChunkReceived(function (res) {
      const uint8Array = new Uint8Array(res.data)
      let text = String.fromCharCode.apply(null, uint8Array)
      text = decodeURIComponent(escape(text))
      let arr = text.split('\n')
      let new_arr = arr[3]
      answer.value = JSON.parse(new_arr.slice(5)).output.text
      //     const uint8Array = new Uint8Array(res.data)
      //     	let text = String.fromCharCode.apply(null, uint8Array)
      // console.log(text,"313113")
      //     	// text = decodeURIComponent(escape(text))
      //     	let object ={}
      //     	if(text.indexOf(":HTTP_STATUS/200") != -1){
      //     		object = JSON.parse(text.split("data:")[1])
      //     	}
      // console.log(object,"objectobject")
    })

    // getChat(data)
    //   .then((res) => {
    //     const { code, data } = res
    //     if (code === 0) {
    //       messagesBack.value.push({
    //         role: 'assistant',
    //         content: data,
    //       })
    //       chatArr.messages.push({ content: data, role: 'assistant' })
    //       answer.value = data
    //       outputText(answer.value)
    //     }
    //   })
    //   .finally(() => {
    //     uni.hideLoading()
    //   })
  }
}

// 流式输出文字
const outputText = (text) => {
  var index = 0
  const streamOutput = () => {
    if (index < text.length) {
      var currentText = text.substring(0, index + 1)
      answer.value = currentText
      index++
    } else {
      clearInterval(timer)
    }
  }
  let timer = setInterval(streamOutput, 20)
}

const jumpEnAnswerPage = () => {
  tnNavPage(`/home-page/agent/en-answer?answerZh=${answer.value}`)
}

//中文转语音
const textToSpeech = () => {
  return new Promise((resolve, reject) => {
    plugin.textToSpeech({
      lang: 'zh_CN',
      tts: true,
      content: answer.value,
      success: function (res) {
        console.log('succ tts', res.filename)
        audioSrc.value = res.filename
        resolve()
      },
      fail: function (res) {
        console.log('fail tts', res)
      },
    })
  })
}

// const stopAudio = () => {
//   innerAudioContext.stop()
// }

// const onPlayIconClick = async () => {
//   await textToSpeech()
//   // 获取当前静音状态
//   // const systemInfo = uni.getSystemInfoSync()
//   // console.log('当前静音状态：' + systemInfo.audioSilence)

//   innerAudioContext.src = audioSrc.value
//   innerAudioContext.play()
//   innerAudioContext.onPlay(() => {
//     console.log('开始播放')
//   })
//   innerAudioContext.onError((err) => {
//     console.log(err.errMsg)
//   })
//   innerAudioContext.onEnded(() => {
//     innerAudioContext = null
//   })
// }

const onPlayIconClick = () => {
  // Chinese中文 | English英文
  webSocketSendMp3(answer.value, 'Chinese').then((res) => {
    let newArr = []
    res.map((item, index) => {
      const arrayBuffer = wx.base64ToArrayBuffer(item)
      const newBuffer = new Uint8Array(arrayBuffer)
      newArr.push(...newBuffer)
    })
    let uint8Array = new Uint8Array(newArr)
    const newUrl = wx.createBufferURL(uint8Array.buffer)
    handleClickVideo(newUrl)
  })
}

const onCopyIconClick = () => {
  uni.setClipboardData({
    data: answer.value,
    success: function () {},
  })
}

const onZanIconClick = () => {
  console.log(voteStatus.value)
  if (voteStatus.value == 0) {
    voteUp(pageId.value).then((res) => {
      const { code, msg } = res
      if (code === 0) {
        uni.showToast({
          title: '已赞',
          duration: 2000,
        })
        getIsVote()
      } else {
        uni.showToast({
          title: msg,
          duration: 2000,
        })
      }
    })
  }
}

const onCaiIconClick = () => {
  if (voteStatus.value == 0) {
    voteDown(pageId.value).then((res) => {
      const { code, msg } = res
      if (code === 0) {
        uni.showToast({
          title: '已踩',
          duration: 2000,
        })
        getIsVote()
      } else {
        uni.showToast({
          title: msg,
          duration: 2000,
        })
      }
    })
  }
}
</script>

<style lang="scss" scoped>
.problem-title {
  padding: 18rpx 24rpx;
  margin: 48rpx 5% 48rpx 0;
  text-align: right;
  font-size: 28rpx;
  line-height: 44rpx;
  color: #fff;
  text-align: left;
  border-radius: 30rpx 0 30rpx 30rpx;
  float: right;
  background: linear-gradient(90deg, #4b49e8 0%, #6b8bfb 100%);
  border-image: linear-gradient(
      180deg,
      rgba(255, 255, 255, 1),
      rgba(255, 255, 255, 0.38)
    )
    2 2;
  max-width: 90%;
}

.wrap {
  width: 90%;
  margin: 0 5%;
  padding: 24rpx;
  border-radius: 0 22rpx 22rpx 22rpx;
  background-color: #fff;
  clear: both;
  font-family:
    PingFang SC,
    PingFang SC;
  font-weight: 400;
  font-size: 28rpx;
  color: #191919;
  line-height: 44rpx;
  text-align: justified;
  font-style: normal;
  text-transform: none;
}

image {
  width: 50rpx;
}

.bottom-bar {
  margin-top: 40rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .left {
    image {
      vertical-align: middle;
      margin-right: 14rpx;
      width: 40rpx;
    }
  }

  .left {
    text {
      vertical-align: middle;
      color: #6b8bfb;
      font-size: 28rpx;
    }
  }

  .right {
    display: flex;

    button {
      background-color: #fff;
      width: 44rpx;
      margin: 0;
      padding: 0;
      position: relative;
      margin-right: 16rpx;

      image {
        position: absolute;
        top: 0;
        left: 0;
      }
    }

    image {
      margin-right: 16rpx;
    }
  }
}
</style>
